package com.xczl.demo.test;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import com.xczl.demo.domain.User;
import com.xczl.demo.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:root-context.xml" })
public class UserServiceTestCase {

	@Autowired
	private UserService userService;

	@Test
	@Transactional
	public void add() {
		User user = createUser();
		userService.addUser(user);
		User user2 = userService.findById(user.getUserId());
		System.out.println(user2.getUserName());
		Assert.assertNotNull(user2);
	}

	private User createUser() {
		User user = new User();
		user.setUserName("user" + RandomUtils.nextInt(1000, 1500));
		// user.setUserName("user1");
		user.setPassword("123456");
		user.setSex(User.SEX_MALE);
		user.setName("猩猩");
		return user;
	}

	@Test
	@Transactional
	public void login() {
		// 注册
		User user = createUser();
		userService.addUser(user);
		// 验证
		User user2 = userService.login(user.getUserName(), user.getPassword());
		Assert.assertNotNull(user2);
	}

	@Test
	@Transactional
	public void update() {
		// 注册
		User user = createUser();
		userService.addUser(user);
		// 修改用户
		user.setName("小华");
		user.setPassword("59789");
		user.setSex(User.SEX_FEMALE);
		user.setUserName("userabc");
		userService.editUser(user);
		// 获取最新信息
		User user1 = userService.findById(user.getUserId());
		// 验证结果
		Assert.assertFalse(StringUtils.equals(user.getPassword(),
				user1.getPassword()));// 密码不相等
		Assert.assertFalse(StringUtils.equals(user.getUserName(),
				user1.getUserName()));// 用户名不相等
		Assert.assertTrue(StringUtils.equals(user.getName(), user1.getName()));// 姓名相等
		Assert.assertTrue(user.getSex().equals(user1.getSex()));// 性别相等
	}

	@Test
	@Transactional
	public void updatePassword() {
		// 注册
		User user = createUser();
		userService.addUser(user);
		String newPassword = "56789";
		String oldPassword = user.getPassword();
		// 修改用户
		userService.modifyPassword(user.getUserId(), oldPassword, newPassword);
		// 获取最新信息
		User user1 = userService.findById(user.getUserId());
		// 验证结果
		Assert.assertTrue(StringUtils.equals(user1.getPassword(), newPassword));// 等于新密码
		Assert.assertFalse(StringUtils.equals(user1.getPassword(), oldPassword));// 不等于旧密码

	}
}
